﻿using System;
using System.Collections.Generic;

class PrimeNumberPrinter
{
    static void Main()
    {      
        Console.Write("请输入上限: ");
        int upperBound = GetInput();
        Console.Write("请输入下限: ");
        int lowerBound = GetInput();

        if (lowerBound > upperBound)
        {
            int temp = lowerBound;
            lowerBound = upperBound;
            upperBound = temp;
            //交换输入的上下限确保上限大于下限
        }

        List<int> primes = GetPrimesInRange(lowerBound, upperBound);
        Console.WriteLine($"\n在 {lowerBound} 和 {upperBound} 之间的素数有 {primes.Count} 个:");
        PrintPrimes(primes);  
        Console.ReadKey();
    }

    static int GetInput()
    {
        while (true)
        {
            if (int.TryParse(Console.ReadLine(), out int number) && number > 0)
            {
                return number;
            }
            Console.Write("请输入正整数");
        }
    }

    // 判断否为素数
    static bool IsPrime(int number)
    {
        if (number <= 1) return false;
        if (number == 2) return true;
        if (number % 2 == 0) return false;

        int boundary = (int)Math.Sqrt(number);
        for (int i = 3; i <= boundary; i += 2)
        {
            if (number % i == 0)
                return false;
        }
        return true;
    }

    static List<int> GetPrimesInRange(int lower, int upper)
    {
        List<int> primes = new List<int>();
        for (int i = lower; i <= upper; i++)
        {
            if (IsPrime(i))
            {
                primes.Add(i);
            }
        }
        return primes;
    }
    static void PrintPrimes(List<int> primes)
    {
        for (int i = 0; i < primes.Count; i++)
        {
            Console.Write($"{primes[i],8}");
            if ((i + 1) % 10 == 0 || i == primes.Count - 1)
            {
                Console.WriteLine();
            }
        }
    }
}